// Copyright 2006 Mloofle Inc. All Rights Reserved.
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.LineNumberReader;
import java.io.RandomAccessFile;
import java.util.LinkedList;

/**
 * Runs a command-line application for searching an index to a corpus.
 */
public class QUIRK {

  /**
   * Run a command-line application for searching an index to a corpus.
   * 
   * @param args the command-line arguments
   */
  public static void main(String[] args) {
    try {
      if (args.length > 0) {
        Util.errExit("QUIRK does not accept arguments");
      }

      Corpus corpus = createCorpusFromIndex();
      CommandState cmdState = new CommandState(corpus);
      LineNumberReader in = new LineNumberReader(new InputStreamReader(
          System.in));
      while (true) {
        System.out.print("??? ");
        String theLine = in.readLine();
        String[] rawCmd = theLine.split(" ");
        LinkedList cmdList = new LinkedList();
        for (int i = 0; i < rawCmd.length; ++i) {
          if (!rawCmd[i].equals("")) {
            cmdList.add(rawCmd[i]);
          }
        }
        if (cmdList.size() > 0) {
          String cmd = (String) cmdList.removeFirst();
          String[] cmdArgs = (String[]) cmdList.toArray(new String[cmdList.size()]);
          cmdState.process(cmd, cmdArgs);
        }
      }
    } catch (OutOfMemoryError e) {
      Util.errExit("Out of memory; the corpus may be too large");
    } catch (Throwable e) {
      Util.errExit("Program terminated unexpectedly");
    }
  }

  private static Corpus createCorpusFromIndex() {
    RandomAccessFile input = null;
    try {
      input = new RandomAccessFile("AIM.out", "r");
      return Corpus.createCorpus(input);
    } catch (FileNotFoundException e) {
      Util.errExit("Index file 'AIM.out' does not exist");
    } catch (IOException e) {
      Util.errExit("Index file 'AIM.out' could not be read from");
    } finally {
      Util.close(input);
    }
    return null;
  }

  /**
   * Not instantiable.
   */
  private QUIRK() {
  }

}
